#include "Framework/Application.h"
#include "Object/NewObject.h"
#include "Misc/CommandLineArgumentsParser.h"
#include "ScriptRuntime/ScriptSubsystem.h"
#include "Output/Console.h"
#include "MainModule/StartUpProject.h"

int main(int argc, char* argv[])
{
    auto App=NewObject<RApplication>();
        
    
    CCommandLineArgumentsParser Parser;

    {
        int32_t Port=-1;
        Parser.AddOption(U"DebugPort",U"port of debug server",Port);
    }
    {
        Parser.AddOption(U"RootFolder",U"Path of folder of project",CGetType<CString>()());
    }

    auto Error=Parser.Parse(argc,argv);
    if(Error.HasValue())
    {
        WH::PrintLine(U"Parse arguments error: ");
        WH::PrintLine(Error.GetValue());
        return 1;
    }

    SApplicationArgument Arguments;
    Arguments.ExecutablePath=SPath(argv[0]);
    Arguments.DefaultFont=Arguments.ExecutablePath.Parent()/U"Content"/U"EngineEditor"/U"Fonts"/U"DroidSerifBold-aMPE.ttf";
    Arguments.FallBackFont=Arguments.ExecutablePath.Parent()/U"Content"/U"EngineEditor"/U"Fonts"/U"SourceHanSansHWSC-Bold.otf";
    Arguments.WorkThreadNum=4;
    //Arguments.bStartDebugServer=Parser.IsOptionSet(U"DebugPort");

    App->Initialize(Arguments);

    if(Parser.IsOptionSet(U"DebugPort"))
    {
        RScriptSubsystem::Get()->StartDebugServer(Parser.GetValue<int32_t>(U"DebugPort"));
        RScriptSubsystem::Get()->MarkAutoExitAppWhenDebuggerDetached();
        WH::PrintLine(U"Waiting for Debugger attaching");
        //wait for debugger to attach
        while(!RScriptSubsystem::Get()->IsDebuggerAttached())
        {
            App->RunOnce();
        }

        WH::PrintLine(U"Debugger attached!");
    }        

    
    SPath RootFolder;
    if(Parser.IsOptionSet(U"RootFolder"))
    {
        RootFolder=Parser.GetValue<CString>(U"RootFolder");
    }
    else
    {
        RootFolder=Arguments.ExecutablePath.Parent()/U"Project";
    }
    StartUpProject(RootFolder);

    return App->Run();
}